<template>
	<div class="dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" :close-on-click-modal="false" width="1010px">
			<el-divider content-position="left">不支持配送区域</el-divider>
			<el-select v-model="state.deliveryArea.country" placeholder="请选择国家" clearable style="width: 200px">
				<el-option v-for="item in state.optionCountry" :key="item.id" :label="item.name" :value="item.name" />
			</el-select>
			<el-cascader v-model="state.deliveryArea.area" :props="state.areaProps" placeholder="请选择地区" clearable style="width: 72%" class="ml5" />
			<el-button type="primary" class="ml5" @click="onAddDeliveryArea"> 添加 </el-button>
			<el-table :data="state.deliveryList" v-loading="state.loading" border class="mt10">
				<el-table-column label="国家" align="center" prop="country" />
				<el-table-column label="省" align="center" prop="province" />
				<el-table-column label="市" align="center" prop="city" />
				<el-table-column label="区、县" align="center" prop="county" />
				<el-table-column label="操作" align="center" prop="operation" fixed="right" width="100">
					<template #default="{ row, $index }">
						<el-popconfirm
							title="您确定删除该数据？此操作不可撤回"
							@confirm="onDeleteDeliveryArea({ freight_template_not_send_id: row.id, $index })"
							width="180px"
						>
							<template #reference>
								<el-button type="primary" link> 删除 </el-button>
							</template>
						</el-popconfirm>
					</template>
				</el-table-column>
			</el-table>
			<PaginationComponent
				v-if="state.total"
				:total="state.total"
				v-model:page="state.queryParams.pageNum"
				v-model:limit="state.queryParams.pageSize"
				@pagination="getList"
			/>
			<el-divider content-position="left">不支持包邮区域</el-divider>
			<el-select v-model="state.freeShippingArea.country" placeholder="请选择国家" clearable style="width: 200px">
				<el-option v-for="item in state.optionCountry" :key="item.id" :label="item.name" :value="item.name" />
			</el-select>
			<el-cascader v-model="state.freeShippingArea.area" :props="state.areaProps" placeholder="请选择地区" clearable style="width: 61%" class="ml5" />
			<el-input
				v-model="state.freeShippingArea.price"
				placeholder="请输入运费"
				clearable
				class="ml5"
				style="width: 100px"
				@input="onVerifiyNumberIntegerPrice"
			/>
			<el-button type="primary" class="ml5" @click="onAddFreeShippingArea"> 添加 </el-button>
			<el-table :data="state.shippingList" v-loading="state.loading1" border class="mt10">
				<el-table-column label="国家" align="center" prop="country" :formatter="formatterCountry" />
				<el-table-column label="省" align="center" prop="province" :formatter="formatterProvince" />
				<el-table-column label="市" align="center" prop="city" :formatter="formatterCity" />
				<el-table-column label="区、县" align="center" prop="county" :formatter="formatterCounty" />
				<el-table-column label="运费" align="center" prop="price" width="100">
					<template #default="{ row }">
						<el-input v-model="row.price" @input="(val: string) => onVerifiyNumberIntegerPrice1(val,row)" @blur="onBlurPrice(row)" />
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center" prop="operation" fixed="right" width="100">
					<template #default="{ row, $index }">
						<el-popconfirm
							title="您确定删除该数据？此操作不可撤回"
							@confirm="onDeleteFreeShippingArea({ freight_template_not_mail_id: row.id, $index })"
							width="180px"
						>
							<template #reference>
								<el-button type="primary" link> 删除 </el-button>
							</template>
						</el-popconfirm>
					</template>
				</el-table-column>
			</el-table>
			<PaginationComponent
				v-if="state.total1"
				:total="state.total1"
				v-model:page="state.queryParams1.pageNum"
				v-model:limit="state.queryParams1.pageSize"
				@pagination="getList1"
			/>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus';
import { reactive, watch } from 'vue';
import { areaApi, freightTemplateApi } from '/@/api';
import { verifiyNumberInteger } from '/@/utils/toolsValidate';

const FreightTemplateApi = freightTemplateApi();
const AreaApi = areaApi();
const state = reactive({
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitLoading: false,
	},
	deliveryList: [] as any,
	shippingList: [] as any,
	queryParams: {
		template_id: '',
		pageNum: 1,
		pageSize: 10,
	},
	queryParams1: {
		template_id: '',
		pageNum: 1,
		pageSize: 10,
	},
	loading: true,
	loading1: true,
	total: 0,
	total1: 0,
	deliveryArea: {
		country: '',
		area: [],
	},
	freeShippingArea: {
		area: [],
		price: '',
		country: '',
	},
	optionCountry: [] as any,
	areaProps: {},
});

watch(
	() => state.deliveryArea.country,
	(e) => {
		if (!e) return;
		const countryData = state.optionCountry.find((item: any) => item.name === state.deliveryArea.country);
		state.areaProps = {
			checkStrictly: true,
			lazy: true,
			lazyLoad(node: any, resolve: any) {
				const {
					data: { id },
					level,
				} = node;
				console.log('哈哈');

				_areaList({ parent_id: level ? id : countryData.id }, level, resolve);
			},
			value: 'name',
			label: 'name',
		};
	}
);
watch(
	() => state.freeShippingArea.country,
	(e) => {
		if (!e) return;
		const countryData = state.optionCountry.find((item: any) => item.name === state.freeShippingArea.country);
		state.areaProps = {
			checkStrictly: true,
			lazy: true,
			lazyLoad(node: any, resolve: any) {
				const {
					data: { id },
					level,
				} = node;
				_areaList({ parent_id: level ? id : countryData.id }, level, resolve);
			},
			value: 'name',
			label: 'name',
		};
	}
);

/********** 触发事件 **********/
// 添加不支持配送区域
const onAddDeliveryArea = () => {
	let areaArray = state.deliveryArea.area;
	if (!state.deliveryArea.country) return ElMessage.warning('请选择国家');
	if (!areaArray.length) return ElMessage.warning('请选择不支持包邮区域');
	if (areaArray.length == 3) {
		let isarea = state.deliveryList.findIndex((item: any) => {
			return item.county == areaArray[2];
		});
		let iscity = state.deliveryList.findIndex((item: any) => {
			return !item.county && item.city == areaArray[1];
		});
		let isprovince = state.deliveryList.findIndex((item: any) => {
			return !item.county && !item.city && item.province == areaArray[0];
		});
		if (isarea > -1) return ElMessage.warning('该区、县已被添加');
		if (iscity > -1) return ElMessage.warning('该区、县已被城市包含');
		if (isprovince > -1) return ElMessage.warning('该区、县已被省份包含');
	} else if (areaArray.length == 2) {
		let isarea = state.deliveryList.findIndex((item: any) => {
			return item.county && item.city == areaArray[1];
		});
		let iscity = state.deliveryList.findIndex((item: any) => {
			return !item.county && item.city == areaArray[1];
		});
		let isprovince = state.deliveryList.findIndex((item: any) => {
			return !item.city && item.province == areaArray[0];
		});
		if (isarea > -1) return ElMessage.warning('该城市已添加了部分区、县');
		if (iscity > -1) return ElMessage.warning('该城市已被添加');
		if (isprovince > -1) return ElMessage.warning('该城市已被省份包含');
	} else {
		let isarea = state.deliveryList.findIndex((item: any) => {
			return item.county && item.city && item.province == areaArray[0];
		});
		let iscity = state.deliveryList.findIndex((item: any) => {
			return item.city && item.province == areaArray[0];
		});
		let isprovince = state.deliveryList.findIndex((item: any) => {
			return item.province == areaArray[0];
		});
		if (isarea > -1) return ElMessage.warning('该省份已添加了部分区、县');
		if (iscity > -1) return ElMessage.warning('该省份已添加了部分城市');
		if (isprovince > -1) return ElMessage.warning('该省份已被添加');
	}
	_freightTemplateNotSendAdd({
		template_id: state.queryParams.template_id,
		country: state.deliveryArea.country,
		province: areaArray[0],
		city: areaArray.length > 1 ? areaArray[1] : '',
		county: areaArray.length > 2 ? areaArray[2] : '',
	});
};
// 删除不支持配送区域
const onDeleteDeliveryArea = (row: any) => {
	_freightTemplateNotSendDelete(row);
};
// 不支持包邮区域运费过滤
const onVerifiyNumberIntegerPrice = (val: string) => {
	state.freeShippingArea.price = verifiyNumberInteger(val);
};
// 不支持包邮区域运费过滤
const onVerifiyNumberIntegerPrice1 = (val: string, row: any) => {
	row.price = verifiyNumberInteger(val);
};
// 不支持包邮区域运费失去焦点
const onBlurPrice = (row: any) => {
	console.log('countryData', row);
	_freightTemplateNotMailEdit({
		...row,
		freight_template_not_mail_id: row.id,
		country: row.country === '----' ? '' : row.country,
		province: row.province === '----' ? '' : row.province,
		city: row.city === '----' ? '' : row.city,
		county: row.county === '----' ? '' : row.county,
	});
};
// 添加不支持包邮区域
const onAddFreeShippingArea = () => {
	let areaArray = state.freeShippingArea.area;
	if (!state.freeShippingArea.country) return ElMessage.warning('请选择国家');
	if (!areaArray.length) return ElMessage.warning('请选择不支持包邮区域');
	if (!state.freeShippingArea.price) return ElMessage.warning('请输入运费');
	if (areaArray.length == 3) {
		let isarea = state.shippingList.findIndex((item: any) => {
			return item.county == areaArray[2];
		});
		let iscity = state.shippingList.findIndex((item: any) => {
			return !item.county && item.city == areaArray[1];
		});
		let isprovince = state.shippingList.findIndex((item: any) => {
			return !item.county && !item.city && item.province == areaArray[0];
		});
		if (isarea > -1) return ElMessage.warning('该区、县已被添加');
		if (iscity > -1) return ElMessage.warning('该区、县已被城市包含');
		if (isprovince > -1) return ElMessage.warning('该区、县已被省份包含');
	} else if (areaArray.length == 2) {
		let isarea = state.shippingList.findIndex((item: any) => {
			return item.county && item.city == areaArray[1];
		});
		let iscity = state.shippingList.findIndex((item: any) => {
			return !item.county && item.city == areaArray[1];
		});
		let isprovince = state.shippingList.findIndex((item: any) => {
			return !item.city && item.province == areaArray[0];
		});
		if (isarea > -1) return ElMessage.warning('该城市已添加了部分区、县');
		if (iscity > -1) return ElMessage.warning('该城市已被添加');
		if (isprovince > -1) return ElMessage.warning('该城市已被省份包含');
	} else {
		let isarea = state.shippingList.findIndex((item: any) => {
			return item.county && item.city && item.province == areaArray[0];
		});
		let iscity = state.shippingList.findIndex((item: any) => {
			return item.city && item.province == areaArray[0];
		});
		let isprovince = state.shippingList.findIndex((item: any) => {
			return item.province == areaArray[0];
		});
		if (isarea > -1) return ElMessage.warning('该省份已添加了部分区、县');
		if (iscity > -1) return ElMessage.warning('该省份已添加了部分城市');
		if (isprovince > -1) return ElMessage.warning('该省份已被添加');
	}
	_freightTemplateNotMailAdd({
		template_id: state.queryParams.template_id,
		country: state.freeShippingArea.country,
		province: areaArray[0],
		city: areaArray.length > 1 ? areaArray[1] : '',
		county: areaArray.length > 2 ? areaArray[2] : '',
		price: state.freeShippingArea.price,
	});
};
// 删除不支持包邮区域
const onDeleteFreeShippingArea = (row: any) => {
	_freightTemplateNotMailDelete(row);
};

/********** 方法事件 **********/
// 打开
const openDialog = (row: any) => {
	state.dialog.isShowDialog = true;
	state.dialog.title = `「${row.name}」运费配置`;
	state.deliveryArea = {
		country: '',
		area: [],
	};
	state.freeShippingArea = {
		area: [],
		price: '',
		country: '',
	};
	state.queryParams = state.queryParams1 = {
		template_id: row.id,
		pageNum: 1,
		pageSize: 10,
	};
	getList();
	getList1();
	_areaList1({ parent_id: 0 });
};
// 刷新列表
const getList = () => {
	state.loading = true;
	_freightTemplateNotSendList(state.queryParams);
};
// 刷新列表
const getList1 = () => {
	state.loading1 = true;
	_freightTemplateNotMailList(state.queryParams1);
};
// 国家字典
const formatterCountry = (row: any) => {
	return row.country || '----';
};
const formatterProvince = (row: any) => {
	return row.province || '----';
};
const formatterCity = (row: any) => {
	return row.city || '----';
};
const formatterCounty = (row: any) => {
	return row.county || '----';
};

/********** 网络请求 **********/
// 国家地区列表
const _areaList1 = (params: Object) => {
	AreaApi.areaList(params).then((res: any) => {
		state.optionCountry = res.data.list;
	});
};
// 国家地区列表
const _areaList = (params: Object, level: number, resolve: (arg0: any) => void) => {
	AreaApi.areaList(params).then((res: any) => {
		let nodes = res.data.list.map((item: any) => ({
			id: item.id,
			name: item.name,
			leaf: level >= 2,
		}));
		resolve(nodes);
	});
};
// 运费模板不配送区域列表
const _freightTemplateNotSendList = (params: Object) => {
	FreightTemplateApi.freightTemplateNotSendList(params)
		.then((res) => {
			state.deliveryList = res.data.list;
			state.total = res.data.info.total;
			state.loading = false;
		})
		.catch(() => (state.loading = false));
};
// 添加运费模板不配送区域
const _freightTemplateNotSendAdd = (params: Object) => {
	FreightTemplateApi.freightTemplateNotSendAdd(params).then(() => {
		ElMessage.success('操作成功！');
		getList();
	});
};
// 删除运费模板不配送区域
const _freightTemplateNotSendDelete = (params: any) => {
	FreightTemplateApi.freightTemplateNotSendDelete(params)
		.then(() => {
			ElMessage.success('操作成功！');
			state.deliveryList.splice(params.index, 1);
		})
		.catch(() => getList());
};
// 运费模板不包邮区域列表
const _freightTemplateNotMailList = (params: Object) => {
	FreightTemplateApi.freightTemplateNotMailList(params)
		.then((res) => {
			state.shippingList = res.data.list;
			state.total1 = res.data.info.total;
			state.loading1 = false;
		})
		.catch(() => (state.loading1 = false));
};
// 添加运费模板不包邮区域
const _freightTemplateNotMailAdd = (params: Object) => {
	FreightTemplateApi.freightTemplateNotMailAdd(params)
		.then(() => {
			ElMessage.success('操作成功！');
			getList1();
		})
		.catch(() => {});
};
// 编辑运费模板不包邮区域
const _freightTemplateNotMailEdit = (params: Object) => {
	FreightTemplateApi.freightTemplateNotMailEdit(params)
		.then(() => {
			ElMessage.success('操作成功！');
		})
		.catch(() => getList1());
};
// 删除运费模板不包邮区域
const _freightTemplateNotMailDelete = (params: any) => {
	FreightTemplateApi.freightTemplateNotMailDelete(params)
		.then(() => {
			ElMessage.success('操作成功！');
			state.shippingList.splice(params.index, 1);
		})
		.catch(() => getList1());
};
/********** 方法向父组件暴露 **********/
defineExpose({ openDialog });
</script>
